package day16_Runnable.demo09例子;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapTask extends Thread{
    private int flag;
    private File file;
    public MapTask(){}
    public MapTask(File file,int flag){
        this.flag=flag;
        this.file=file;
    }
    @Override
    public void run(){
        try {
            BufferedReader br = new BufferedReader(
                    new FileReader(file.getAbsolutePath()));
            HashMap<String, Integer> map = new HashMap<>();
            String line;
            while ((line=br.readLine())!=null){
                String[] split = line.split(",");
                if(split.length==5){
                    String clazz = split[4];
                    //分类聚合
                    if(map.containsKey(clazz)){
                        map.put(clazz,map.get(clazz)+1);
                    }else {
                        map.put(clazz,1);
                    }
                }


            }
            //把结果写入到文件中
            BufferedWriter bw = new BufferedWriter(
                    new FileWriter("E:\\csw\\Demo\\a\\part-"+flag));
            Set<Map.Entry<String, Integer>> entries = map.entrySet();
            for (Map.Entry<String, Integer> entry : entries) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                String s=key+":"+value;
                bw.write(s);
                bw.newLine();
            }
            bw.close();
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
